package net.cloudcodex.server.service;

import java.util.Collection;
import java.util.List;
import java.util.logging.Logger;

import net.cloudcodex.server.Context;
import net.cloudcodex.server.data.AdvancedDAO;
import net.cloudcodex.server.data.Data;
import net.cloudcodex.server.data.Data.Notification;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.Query.FilterOperator;

/**
 * Abstract class for services.
 * @author Thomas
 */
public class AbstractService {

	/**
	 * Logger.
	 */
	protected final Logger logger = Logger.getLogger(getClass().getName());

	/**
	 * DAO.
	 */
	protected final AdvancedDAO dao;

	/**
	 * @param store Google AppEngine datastore.
	 */
	public AbstractService(DatastoreService store) {
		dao = new AdvancedDAO(store);
	}
	
	/**
	 * Search notifications associated to a key.
	 * @param key key of the notification recipient.
	 * @return notifications associated to a key.
	 */
	public List<Notification> getNotifications(Context context, Key key) {
		
		return dao.asListOfNotifications(context, dao.addNotificationFilterOnTo(
				dao.queryNotification(), FilterOperator.EQUAL, key), null);
	}

	/**
	 * Utility method to create string from data.
	 */
	public String toStringKeys(Collection<? extends Data> datas) {
		if(datas == null) {
			return null;
		}
		final StringBuffer buffer = new StringBuffer("[");
		for(Data data : datas) {
			if(buffer.length() != 1) {
				buffer.append(", ");
			}
			buffer.append(data == null ? null : data.getKey());
		}
		buffer.append("]");
		
		return buffer.toString();
	}
}
